 /*--------------------------------------------------------
  * DOI Function for text
  * For now just set the text with red color
  * as the highest interest(highest number)
  * TODO: Mike would replace it with the real one here
  *-----------------------------------------------------*/
function DOIText($element){
  colorHighestDOI = "#FF0000";
  return ($element.attr('fill') == colorHighestDOI ? 1 : 0);
}

function getX($element){
  var t = $element.attr("transform");
  if(t != null){
    t = t.replace(/[a-zA-Z()]+/g,'').split(',');
    return parseFloat(t[0]);
  }else return false;
}

function getY($element){
  var t = $element.attr("transform");
  if(t != null){
    t = t.replace(/[a-zA-Z()]+/g,'').split(',');
    return parseFloat(t[1]);
  }else return false;
}

//config the collaped text
var textIcon = {
  w: 11,
  h: 15
};

var collapseEnabled = true;

/*
 * Enables or disables collapsing of text. Animates between the two states.
 */
function setTextCollapse(enabled) {
  collapseEnabled = enabled;

  var tile = d3.select($("g.text-dot-container").parent()[0]);

  if (enabled) {
    computeCollapseGroups(tile);
  } else {
    tile.selectAll("text.point_label").each(function(f) {
      if (f.data.group) {
        delete f.data.group;
      }
    });
  }

  applyCollapseGroups(tile);
}

/* ----------------------------------------------------------------
 * Function textCollapse: collapses all the collided texts into dot
 * -------------------------------------------------------------*/
function textCollapse(e) {
  $(e.tile.element).parent().parent().attr('class','layer layer2');

  var tile = d3.select(e.tile.element);
  var container = tile.append('g')
      .attr('class','text-dot-container');

  computeCollapseGroups(tile);
  applyCollapseGroups(tile, container);
}

function computeCollapseGroups(tile) {
  function featuresCollide(a, b) {
    if (a == b) {
      return false;
    }

    var sensitivity = 0.8;
    var boxA = a.element.getBoundingClientRect();
    var boxB = b.element.getBoundingClientRect();
    var dhMax = (boxA.height + boxB.height) / 2;
    var dwMax = (boxA.width + boxB.width) / 2;
    var dx = Math.abs(boxA.left - boxB.left);
    var dy = Math.abs(boxA.top - boxB.top);

    return (dx <= sensitivity * dwMax && dy <= sensitivity * dhMax);
  }

  var featureGroupCount = 0;

  function collapseFeatures(a, b, groups, out) {
    var hasA = a.data.group;
    var hasB = b.data.group;

    if (!hasA && !hasB) {
      var group = ++featureGroupCount;
      a.data.group = group;
      b.data.group = group;
      out.push(a);
      out.push(b);
    } else if (!hasA) {
      a.data.group = b.data.group;
      out.push(a);
    } else if (!hasB) {
      b.data.group = a.data.group;
      out.push(b);
    }
  }

  var collapsedFeatures = [];
  var map = {};

  var features = [];
  tile.selectAll("text.point_label").each(function(f) {
    features.push(f);
  });

  for (var i = 0; i < features.length; i++) {
    for (var j = i + i; j < features.length; j++) {
      if (featuresCollide(features[i], features[j])) {
        collapseFeatures(features[i], features[j], map, collapsedFeatures);
      }
    }
  }
}

function applyCollapseGroups(tile) {
  var container = tile.select("g.text-dot-container");
  var features = [];

  tile.selectAll("text.point_label").each(function(f) {
    features.push(f);
  });

  function translation(f) {
    return "translate(" + f.data.geometry.coordinates.x + "," + f.data.geometry.coordinates.y + ")";
  }

  var group = container.selectAll("g.text-collapse-group")
      .data(features.filter(function (f) { return f.data.group; }), function (f) { return f.element; });

  var enterGroup = group.enter()
      .append('g')
      .attr('class', 'text-collapse-group')
      .each(function(d) {
        d3.select(d.element)
          .transition()
          .each("end", function() {
            d3.select(this)
              .attr("transform", translation(d))
              .style("display", "none");
            })
          .style("opacity", 0.0)
          .attr("transform", function() { return translation(d) + " scale(0)"; });
      });
  enterGroup.append('rect')
    .attr('class', function(d) { return 'text-collapse-group-' + d.group + ' text-collapse-group'; })
    .attr('width', textIcon.w)
    .attr('height', textIcon.h)
    .attr('x', function(d) { return d.data.geometry.coordinates.x; })
    .attr('y', function(d) { return d.data.geometry.coordinates.y; })
    .attr('transform', 'translate(-' + (textIcon.w/1.9) + ',-' + (textIcon.h/1.5) + ')')
    .attr('rx',1)
    .attr('ry',1)
    .style('stroke', function(d) { return d.data.style.label.color; });
  enterGroup.append('text')
    .attr('class',  function(d) { return 'text-collapse-group-' + d.data.group + ' text-collapse-group'; })
    .attr('transform', function(d) { return d3.select(d.element).attr('transform'); })
    .attr('title', function(d) { return d.data.properties.name; })
    .style('fill', function(d) { return d.data.style.label.color; })
    .text("T");
  enterGroup
    .style("opacity", 0.0)
    .transition()
    .style("opacity", 1.0);

  group.exit()
      .each(function(d) {
        d3.select(d.element)
          .attr("transform", translation(d) + " scale(0)")
          .style("display", "block")
          .transition()
          .attr("transform", function () { return translation(d) + " scale(1)"; })
          .style("opacity", 1.0);
      })
      .remove();
}
